package com.sxw.hw_student.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxw.hw_student.system.entity.SysMenu;
import com.sxw.hw_student.system.entity.SysRoleMenu;
import com.sxw.hw_student.system.entity.SysUserRole;
import com.sxw.hw_student.system.service.ISysMenuService;
import com.sxw.hw_student.system.service.ISysRoleMenuService;
import com.sxw.hw_student.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  菜单管理 Controller
 * </p>
 */
@RestController
@RequestMapping("/sysMenu")
public class SysMenuController {

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Autowired
    private ISysRoleMenuService roleMenuService;


    // 获取所有菜单
    @GetMapping
    public List<SysMenu> getAllMenus() {
        return menuService.list();
    }

    // 添加菜单
    @PostMapping
    public ResponseEntity<?> addMenu(@RequestBody SysMenu menu) {
        boolean saved = menuService.save(menu);
        return saved ? ResponseEntity.ok().build() : ResponseEntity.status(500).body("添加失败");
    }

    // 更新菜单
    @PutMapping("/{id}")
    public ResponseEntity<?> updateMenu(@PathVariable Integer id, @RequestBody SysMenu menu) {
        menu.setMenuId(id);
        boolean updated = menuService.updateById(menu);
        return updated ? ResponseEntity.ok().build() : ResponseEntity.status(500).body("更新失败");
    }

    // 删除菜单
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteMenu(@PathVariable Integer id) {
        boolean deleted = menuService.removeById(id);
        return deleted ? ResponseEntity.ok().build() : ResponseEntity.status(500).body("删除失败");
    }

    // 根据角色获取菜单
    @GetMapping("/byRole/{roleId}")
    public List<SysMenu> getMenusByRole(@PathVariable Integer roleId) {
        return menuService.getMenusByRoleId(roleId);
    }

    // 分配菜单给指定用户的角色
    @PostMapping("/assign")
    public ResponseEntity<?> assignMenusToUsers(@RequestBody Map<String, List<Integer>> request) {
        List<Integer> menuIds = request.get("menuIds");
        List<Integer> userIds = request.get("userIds");

        if (menuIds == null || userIds == null || menuIds.isEmpty() || userIds.isEmpty()) {
            return ResponseEntity.badRequest().body("菜单或用户列表不能为空");
        }

        Set<SysRoleMenu> roleMenusToSave = new HashSet<>();

        for (Integer userId : userIds) {
            List<SysUserRole> userRoles = userRoleService.list(
                    new QueryWrapper<SysUserRole>().eq("user_id", userId));

            for (SysUserRole userRole : userRoles) {
                Long roleId = userRole.getRoleId();
                for (Integer menuId : menuIds) {
                    SysRoleMenu roleMenu = new SysRoleMenu();
                    roleMenu.setRoleId(roleId.intValue());
                    roleMenu.setMenuId(menuId);
                    roleMenusToSave.add(roleMenu);
                }
            }
        }

        for (SysRoleMenu rm : roleMenusToSave) {
            roleMenuService.remove(new QueryWrapper<SysRoleMenu>()
                    .eq("role_id", rm.getRoleId()).eq("menu_id", rm.getMenuId()));
        }

        boolean result = roleMenuService.saveBatch(new ArrayList<>(roleMenusToSave));
        return result ? ResponseEntity.ok("分配成功") : ResponseEntity.status(500).body("分配失败");
    }



}
